package com.fanyu.framework.utils;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.google.common.base.Joiner;

public class UrlUtil {

    public static String asUrlParams(LinkedHashMap<String, String> source) {
        LinkedHashMap<String, String> tmp = new LinkedHashMap<>();
        // java8 语法
        source.forEach((k, v) -> {
            if (k != null) {
                tmp.put(k, v);
            }
        });
        return Joiner.on("&").useForNull("").withKeyValueSeparator("=").join(tmp);
    }

    /**
     * 将url参数转换成map
     *
     * @param param aa=11&bb=22&cc=33
     * @return
     */
    public static LinkedHashMap<String, Object> getUrlParams(String param) {
        LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>(0);
        if (StringUtils.isBlank(param)) {
            return map;
        }
        String[] params = param.split("&");
        for (int i = 0; i < params.length; i++) {
            String[] p = params[i].split("=");
            if (p.length == 2) {
                map.put(p[0], p[1]);
            }
        }
        return map;
    }

    /**
     * 将map转换成url
     *
     * @param map
     * @return
     */
    public static String getUrlParamsByMap(LinkedHashMap<String, String> map) {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            sb.append(entry.getKey() + "=" + entry.getValue());
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = StringUtils.substringBeforeLast(s, "&");
        }
        return s;
    }

}
